package cn.tedu.lucky.draw.server.service.Impl;

import cn.tedu.lucky.draw.server.common.enums.DrawEnum;
import cn.tedu.lucky.draw.server.protrocol.po.ActivityPrize;
import cn.tedu.lucky.draw.server.repository.ActivityPrizeRepository;
import cn.tedu.lucky.draw.server.service.IPrizeService;
import cn.tedu.lucky.draw.server.common.enums.ErrorEnum;
import cn.tedu.lucky.draw.server.common.handler.DrawException;
import cn.tedu.lucky.draw.server.protrocol.po.Prize;
import cn.tedu.lucky.draw.server.protrocol.query.PrizeQuery;
import cn.tedu.lucky.draw.server.repository.PrizeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class PrizeServiceImpl implements IPrizeService {

    @Autowired
    private PrizeRepository prizeRepository;
    List<Prize> prizeList;

    @Override
    public List<Prize> findAll(PrizeQuery prizeQuery) {
        if (prizeList==null){
            prizeList = prizeRepository.findAll();
        }
        String name = prizeQuery.getName();
        Integer status = prizeQuery.getStatus();
        return prizeList.stream().filter(
                prize -> (name == null || name =="" ||name.equals(prize.getName()))
        ).filter(
                prize -> (status ==null || status.equals(prize.getStatus()))
        ).collect(Collectors.toList());
    }

    @Override
    public void save(Prize prize) {
        LocalDateTime now = LocalDateTime.now();
        prize.setCreateTime(now);
        prize.setUpdateTime(now);
        Prize save = prizeRepository.save(prize);
        if (save == null) {
            throw new DrawException(ErrorEnum.SYSTEM_ERROR);
        }
        prizeList=null;
    }

    @Autowired
    private ActivityPrizeRepository activityPrizeRepository;

    @Override
    public List<Prize> findPrizeByActivityId(Long id) {
        List<ActivityPrize> activityPrizeList = activityPrizeRepository.findByActivityId(id);
        List<Long> ids = activityPrizeList.stream().map(ActivityPrize::getPrizeId).collect(Collectors.toList());
        List<Prize> prizeList = prizeRepository.findAllById(ids);
        return prizeList;
    }

    @Override
    public List<Prize> noBondPrize(Long id) {
        List<ActivityPrize> activityPrizes = activityPrizeRepository.findByActivityId(id);
        ArrayList<Long> excludeIds = new ArrayList<>();
        for (ActivityPrize activityPrize : activityPrizes) {
            excludeIds.add(activityPrize.getPrizeId());
        }
        //奖品状态
        Integer status = Integer.valueOf(DrawEnum.ENABLE.getCode());
        if (excludeIds.size()==0) {
            return prizeRepository.findByStatusEquals(status);
        }
        return prizeRepository.findByIdNotInAndStatusEquals(excludeIds,status);
    }

}
